package com.flc.archive.writer;

import com.flc.archive.Archive;
import com.flc.archive.config.AppConfig;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/** 
 * 任务管理 
 * @author admin_Hzw 
 * 
 */  
public class TimerManager4File {

    /**
     * 定时多久 ms
     */
    private static final int PERIOD_DAY = 24 * 60 * 60 * 1000;

    private static final Logger logger = LoggerFactory.getLogger(TimerManager4File.class);


    public TimerManager4File() {

        AppConfig.FileCfg fileCfg = AppConfig.getInstance().getFileCfg();
        long initDelay  = getTimeMillis(fileCfg.getChangeFileTimeEveryday()) - System.currentTimeMillis();
        initDelay = initDelay > 0 ? initDelay : PERIOD_DAY + initDelay;

        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("TimerManager4File-%d").daemon(true).build());
        executorService.scheduleAtFixedRate(() -> {
            try {
                Archive.trajectoryWriter.newDailyFile();
                Archive.reportWriter.newDailyFile();
                Archive.diagnosisWriter.newDailyFile();
                //Archive.simpleWriter.newDailyFile();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }, initDelay, PERIOD_DAY, TimeUnit.MILLISECONDS);

        logger.info("将于" + initDelay/1000 + "s后切换到下一天文件");

    }

    /**
     * 获取指定时间对应的毫秒数
     * @param time "HH:mm:ss"
     * @return 相隔时间
     */
    private static long getTimeMillis(String time) {
        try {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            DateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);
            return curDate.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

}